#!/usr/bin/env node

var cp = require('child_process')
var path = require('path')
var packageCfg = require('../package.json')
var installCfg = require('./config')
var PackageDb = require('./db')
var db = new PackageDb(installCfg.dbfile).load()

const NPM_I_INIT = process.env.NPM_I_INIT === '1' ? true : false
const NPM_I_RELEASE = process.env.NPM_I_RELEASE === '1' ? true : false

function contains(names, name) {
  for (var n of names) {
    if (n === name) {
      return true
    }
  }
  return false
}

function installDependencies() {
  if (packageCfg.dependencies) {
    for (var name in packageCfg.dependencies) {
      if (!db.contains(name, packageCfg.dependencies[name]) && !contains(installCfg.natives, name)) {
        cp.spawnSync('npm', [
          'install', '--verbose', name + '@' + packageCfg.dependencies[name]
        ], { 
          cwd: installCfg.appHome, 
          stdio: 'inherit' 
        })
        db.add(name, packageCfg.dependencies[name]).dump()
      }
    }
  }
}

function installDevDependencies() {
  if (packageCfg.devDependencies) {
    for (var name in packageCfg.devDependencies) {
      if (!db.contains(name, packageCfg.devDependencies[name]) && !contains(installCfg.natives, name)) {
        cp.spawnSync('npm', [
          'install', 
          '--verbose', 
          name + '@' + packageCfg.devDependencies[name]
        ], { 
          cwd: installCfg.appHome, 
          stdio: 'inherit'
        })
        db.add(name, packageCfg.devDependencies[name]).dump()
      }
    }
  }
}

function clean() {
  cp.spawnSync('rm', [
    '-r', 
    '-f',
    path.join(installCfg.appHome, 'node_modules')
  ], { 
    cwd: installCfg.appHome,
    stdio: 'inherit' 
  })
  cp.spawnSync('mkdir', [
    '-p', 
    path.join(installCfg.appHome, 'node_modules')
  ], { 
    cwd: installCfg.appHome,
    stdio: 'inherit' 
  })
  db.clean()
}

function main() {
  if (NPM_I_INIT) {
    clean()
  }
  if (!NPM_I_RELEASE) {
    installDevDependencies()
  }
  installDependencies()
}

main()